#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QKeyEvent>
#include <QFont>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow) {
    ui->setupUi(this);
    setWindowTitle("Virtual File System (CMD Style)");
    resize(800, 600);

    // 初始化虚拟磁盘
    vdisk = new VirtualDisk("vdisk.bin");
    if (!vdisk->load()) {
        appendOutput("Creating new virtual disk: vdisk.bin");
        vdisk->create();
    } else {
        appendOutput("Loaded virtual disk: vdisk.bin");
    }

    // 初始化命令处理器
    cmdHandler = new CommandHandler(vdisk, this);
    connect(cmdHandler, &CommandHandler::outputGenerated, this, &MainWindow::appendOutput);
    connect(cmdHandler, &CommandHandler::clearRequested, this, &MainWindow::clearOutput);

    // 初始化样式
    initStyle();

    // 连接输入框回车事件
    connect(ui->cmdInput, &QLineEdit::returnPressed, this, &MainWindow::onCommandEntered);

    // 初始提示
    appendOutput("Virtual File System Simulator");
    appendOutput("Supported commands: MD, CD, RD, MK, DEL, DIR, INFO, CLEAR, EXIT");
    appendOutput("Current directory: \\");
    appendOutput("> ");
}

MainWindow::~MainWindow() {
    vdisk->save();
    delete cmdHandler;
    delete vdisk;
    delete ui;
}

void MainWindow::initStyle() {
    // 设置CMD风格字体（等宽字体）
    QFont font("Consolas", 10);
    ui->outputDisplay->setFont(font);
    ui->cmdInput->setFont(font);

    // 输出区域设置
    ui->outputDisplay->setReadOnly(true);
    ui->outputDisplay->setStyleSheet("background-color: black; color: lightgreen;");
    ui->outputDisplay->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);

    // 输入区域设置
    ui->cmdInput->setStyleSheet("background-color: black; color: lightgreen; border: 1px solid lightgreen;");
    ui->cmdInput->setFocus();

    // 布局调整
    ui->verticalLayout->setContentsMargins(5, 5, 5, 5);
    ui->verticalLayout->setSpacing(2);
}

void MainWindow::onCommandEntered() {
    QString command = ui->cmdInput->text().trimmed();
    if (command.isEmpty()) {
        appendOutput("> ");
        ui->cmdInput->clear();
        return;
    }

    // 显示输入的命令
    appendOutput(command);

    // 处理命令
    cmdHandler->processCommand(command);

    // 重置输入框并显示提示符
    ui->cmdInput->clear();
    appendOutput("> ");
}

void MainWindow::appendOutput(const QString &text) {
    ui->outputDisplay->insertPlainText(text + "\n");
    ui->outputDisplay->moveCursor(QTextCursor::End);
}

void MainWindow::clearOutput() {
    ui->outputDisplay->clear();
    appendOutput("> ");
}
